<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<!--<script type="text/javascript" src="<?php //echo base_url()?>js/elable_polygon.js"></script>-->
<script type="text/javascript" src="<?php echo base_url()?>js/elable_popup_polygon.js"></script> 
<script type="text/javascript"><!--
    var map;
    var marker;
    var overlay;
    var gmarkers = [];
    var label;
    var current_map_state;
    //var label_polygon;
    var label_popup_polygon;
    var map_zoomlevel; // global map zoom level (integer)
    var show_polygons = 0; // global show polygon status (1 means polygon showed, 0 polygon destroyed)
    var polygon_fetched = 0; // global status whether the polygon data has been fetched from database    
    var network_polygons = []; // global array containing network polygons
    var show_markers = 1; // global show marker status (1 means polygon showed, 0 polygon destroyed)
    var marker_fetched = 0; // global status whether the marker data has been fetched from database
    // Define the overlay, derived from google.maps.OverlayView
    function Label(opt_options) {
     // Initialization
     this.setValues(opt_options);

     // Label specific      
     var div = this.div_ = document.createElement('div');
     div.setAttribute('id','popup');          
     var div1 = document.createElement('div');
     var div2 = document.createElement('div');
     div1.setAttribute('id','div1');         
     
     div1.style.cssText = 'font-size:12px;line-height:16px;background:#FFFFFF;color:#000000;border: 1px solid #000000;width:160px;padding:3px 7px;';
     div2.setAttribute('id','div2');
     div2.style.cssText = 'font-size:11px;line-height:22px;font-weight:bold; background:#000000;color:#FFD455;padding:0 7px;';
     div.appendChild(div1);
     div.appendChild(div2);
     div.style.cssText = 'position: absolute; display: none; z-index:2000;';
    };
    
    Label.prototype = new google.maps.OverlayView;
    
    // Implement onAdd
    
    Label.prototype.onAdd = function() {
     var pane = this.getPanes().floatPane;
     pane.appendChild(this.div_);

     // Ensures the label is redrawn if the text or position is changed.
     var me = this;
     /*this.listeners_ = [
       google.maps.event.addListener(this, 'mouseover',
           function() { me.draw(); }),
       google.maps.event.addListener(this, 'mouseout',
           function() { me.draw(); })
     ];*/
    };
    

    // Implement onRemove
    Label.prototype.onRemove = function() {
     this.div_.parentNode.removeChild(this.div_);

     // Label is removed from the map, stop updating its position/text.
     /*for (var i = 0, I = this.listeners_.length; i < I; ++i) {
       google.maps.event.removeListener(this.listeners_[i]);
     }*/
    }; 
    
    // Implement draw
    Label.prototype.draw = function() {
     var projection = this.getProjection();
     var position = projection.fromLatLngToDivPixel(this.get('position'));

     var div = this.div_;
     div.style.left = position.x + 'px';
     div.style.top = position.y + 'px';
     div.style.display = 'block';    
        
     document.getElementById('div1').innerHTML = this.get('text1').toString();
     document.getElementById('div2').innerHTML = this.get('text2').toString();
    };
        
function check_polygon(map_zoomlevel){
  if(map_zoomlevel > 6){
    if(show_polygons == 0){
    show_polygons = 1;
    }
    
  }else{

    show_polygons = 0;
  }
  // check if need to fetch poly
    if(show_polygons == 1){
      if(polygon_fetched == 0){
    fetch_polygon();
    polygon_fetched = 1;
      }else{
    $.each(network_polygons, function(i,item){
      item.setMap(map);
    });
      }
    }else{
      $.each(network_polygons, function(i,item){
    item.setMap(null);
      });
    }
}

function check_marker(map_network_zoomlevel){
	
	  /*if(map_network_zoomlevel > 12){
	    if(show_markers == 0){
	    show_markers = 1;
	    }
	    
	  }else{

	    show_markers = 0;
	  }*/
	  // check if need to fetch poly
	    if(show_markers == 1){
	      if(marker_fetched == 0){	    	
			fetch_marker();
	    	marker_fetched = 1;
	      }else{
	    $.each(gmarkers, function(i,item){
	      item.setMap(map);
	    });
	      }
	    }else{
	      $.each(gmarkers, function(i,item){
	    item.setMap(null);
	      });
	    }
}
function fetch_marker(){
	  if(marker_fetched == 0){
		 
	    $.getJSON("<?php echo site_url('json_request/get_directory')?>",function(data){
	      $.each(data, function(i,item){	
		  	create_marker(item.latitude, item.longitude, 'mcspin.png' , 'mcspin_shadow.png' , item.company , (item.company_website==''?'N/A':item.comany_website), item.company_slug_name);    
	      });

	    });      
	    marker_fetched = 1;
	  }else{
	  }
}
/*
function undraw_polygons(polygon_undrawed){
  polygon_undrawed.setMap( null);
}
function fetch_polygon(){
  if(polygon_fetched == 0){
    $.getJSON("<?php echo site_url('json_request/network_polygon')?>",function(data){ 
      $.each(data, function(i,item){          
    array_path = item.path.split('#');
    item.path = array_path;
    create_polygon(item, 1000 - i);
      });

    });      
    polygon_fetched = 1;
  }else{
  }
}*/    
  $(document).ready(function(){        
    initialize();    
   /* $('#address').each(function() {
        var default_value = this.value;
        $(this).focus(function() {
            if(this.value == default_value) {
                this.value = '';
            }
        });
        $(this).blur(function() {
            if(this.value == '') {
                this.value = default_value;
            }
        });
    }); */

    /* show/hide control panel*/      
    
  }); // end onready
  
    function initialize() {
        
        geocoder = new google.maps.Geocoder();
        <?php if(!empty($current_latitude) && !empty($current_longitude)){ ?>
        var startLatLng = new google.maps.LatLng(<?php echo $current_latitude ?>, <?php echo $current_longitude ?>);
	  <?php if(!empty($current_zoom)){?>
	var ZoomStart = <?php echo $current_zoom; ?>;
	  <?php }else{ ?>
	    var ZoomStart = 12;
	  <?php } ?>
        <?php }else{ ?>
        var startLatLng = new google.maps.LatLng(-26.17999000000000, 28.12615000000000);
	var ZoomStart = 6;
        <?php } ?>		
        var myOptions = {
            zoom: ZoomStart,
            center: startLatLng,
            mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.DEFAULT
            },
            navigationControlOptions: {
                style: google.maps.NavigationControlStyle.DEFAULT
            },
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map(document.getElementById("map"), myOptions);
        check_marker(1);
        //alert(gmarkers[0].mycategory);
        google.maps.event.addListener(map, 'zoom_changed', function() {
           map_zoomlevel = map.zoom;
	       map_state();
	       check_marker(map_zoomlevel);
          //check_polygon(map_zoomlevel);
        });
        google.maps.event.addListener(map, 'center_changed', function() {
          map_zoomlevel = map.zoom;
	  map_state();
	  //check_marker(map_zoomlevel);
          //check_polygon(map_zoomlevel);
        }); 
        
        <?php if(!empty($address) && !empty($province)){ ?>
              codeAddress();
        <?php } ?>
	map_state();
    }
function goto_detail(the_link){
	//alert(current_map_state);
	$.post('<?php echo site_url('crime_map/save_state');?>',{value: current_map_state}, function(data) {
	  window.location = the_link;
      });
      return false;
}
function map_state(){
	current_map_state = map.center+'/'+map.zoom;
}

var tempLabel;     
var tOut;  

function removeTheLabel(){
    if (tempLabel != null){
        tempLabel.unbind('map');
        tempLabel.setMap(null);
        tempLabel = null;      
    }          
}

function create_marker(lat, lon, icon_image, icon_shadow, title, website, seourl){
    if(icon_shadow != null){
        var shadow_image = icon_shadow.split(".");    
    }else{
        var str = 'other.png';
        var shadow_image = str.split(".");
        //alert(shadow_image[0]);
    }
	
    //var temp_content = content.split(" ");
    //var temp_content_one = date.split("-");
    //var temp_date = temp_content_one[0] +"/"+temp_content_one[1]+"/"+ temp_content_one[2];
    //var temp_time = temp_content[1].substring(0,5);    
   
   // var temp_time;
    //temp_time = time.split(" ");
   /* if(time.substring(0,7) == 'Unknown' ){
        temp_time = '';    
    }else{
        temp_time = ' at ' + time;    
    }*/
    //var real_content = temp_date + ' @ ' + temp_time + '<br /> <a style="color:white" href="<?php //echo site_url('crime_report/detail')?>/' + crime_id + '"> > click for more</a>';   
	
    //var real_content = '<a style="color:white" href="<?php//echo site_url();?>' + seourl + '">' + website + ' >></a>';    
	//var new_title = '<a onclick="goto_detail(this); return false;" href="<?php//echo site_url()?>' + seourl + '">' + title + '</a>';
	var real_content = '<a style="color:#FFD455" onclick="goto_detail(this); return false;" href="<?php echo site_url()?>' + seourl + '"> View detail </a>';
	var new_title = title;
	    
    var shadow = new google.maps.MarkerImage(
    '<?php echo base_url(); ?>image/point/'+shadow_image[0]+'.png',
        // The shadow image is larger in the horizontal dimension
        // while the position and offset are the same as for the main image.
        new google.maps.Size(44, 14),
        new google.maps.Point(0,0),
        new google.maps.Point(0, 15));
		
	    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lon), 
        map: map,            
        title: title,
        icon: '<?php echo base_url(); ?>image/point/'+icon_image,
        shadow: shadow  
    });

   // marker.mycategory = crime_type;                                 
   // marker.myname = title;
    
    google.maps.event.addListener(marker, "mouseover", function() {  
        clearTimeout(tOut);
        removeTheLabel();
        label = new Label({
                map: map
        }); 
        if (document.getElementById('popup') == null){
            label.bindTo('position', marker, 'position');        
            label.set('text1', new_title);
            label.set('text2', real_content); 
        }else {
            document.getElementById('popup').style.display = 'block'; 

            label.bindTo('position', marker, 'position');        
            label.set('text1', new_title);
            label.set('text2', real_content);
            //document.getElementById('popup').style.display = 'block';
            //setTimeout(removeTheLabel, 5000);    
        } 
        tempLabel = label;
        delete label;
    });
    
    google.maps.event.addListener(marker, "mouseout", function() {  
        tOut = setTimeout(removeTheLabel, 5000);
    });
    
    gmarkers.push(marker);
}

$('#popup').mouseover(function() {
  clearTimeout(tOut);
});
$('#popup').mouseout(function() {
  tOut = setTimeout(removeTheLabel, 2000);
});

function deleteOverlays() {
    if (gmarkers) {
      for (i in gmarkers) {
        gmarkers[i].setMap(null);
      }
      gmarkers.length = 0;
    }
    if (document.getElementById('popup') != null){
        document.getElementById('popup').style.display = 'none';
    }
}

function codeAddress() {    
    /* no province
    var address = document.getElementById("address").value; 
    */
    <?php if(!empty($address) && !empty($province)){ ?>
              var address = "<?php echo $address.', '.$province; ?>";
    <?php }else{ ?>
    
    var street_address = document.getElementById("address").value;    
    var province = document.getElementById("province").value;
    var address = street_address+', '+province;
    <?php } ?>
    marker = new google.maps.Marker({        
        map: map,        
        title:"Address Location",
        icon: '<?php echo base_url(); ?>image/point/pin_point.png',
        shadow: shadow  
    });    
    var shadow = new google.maps.MarkerImage('<?php echo base_url(); ?>image/point/pin_point_shadow.png');
    document.getElementById('message').style.display = 'block';
    document.getElementById('message').innerHTML = '<span class="r"><a href="#" onclick="hide_message()"><img src="<?php echo base_url(); ?>xhtml/img/x.gif" /></a></span>';
    if (geocoder) {
        geocoder.geocode( { 'address': address}, function(results, status) {
            document.getElementById("message").innerHTML = '';
            if (status == google.maps.GeocoderStatus.OK) {
                map.setZoom(13);
                map.setCenter(results[0].geometry.location);
                marker.setPosition(results[0].geometry.location); 
                if(results.length > 1){                
                    document.getElementById("message").innerHTML += "Found " +results.length +" results";
                    // Loop through the results, placing markers
                    for (var i=0; i<results.length; i++) {
                        document.getElementById("message").innerHTML += "<br>" + (i+1) 
                        + ": <a href='javascript:map.setCenter(new google.maps.LatLng"
                        + results[i].geometry.location + "); marker.setPosition(new google.maps.LatLng" + results[i].geometry.location + ");'>" 
                        + results[i].formatted_address + "</a>";                    
                    }
                }else{
                    document.getElementById('message').style.display = 'none';    
                }
                // centre the map on the first result
                map.setCenter(results[0].geometry.location);
                marker.setPosition(results[0].geometry.location);
            } else {
                //document.getElementById("message").innerHTML += "Geocode was not successful for the following reason: " + status;
                document.getElementById("message").innerHTML += "Error! Google Geocode reports Zero Results found Enter a City/Town to improve your results Or check the address details entered for errors";
            }
        });
    }
}
function hide_message(){
    document.getElementById('message').style.display = 'none';        
}

function hide_popup_marker(){
    document.getElementById('popup').style.display = 'none';    
}

function hide_popup_polygon(){
    document.getElementById('div_network').style.display = 'none';    
}

function create_polygon(raw_poly_data, z_index){
  var poly_points = [];
  var bounds = new google.maps.LatLngBounds();
  $.each(raw_poly_data.path , function(i,point){
    point = point.replace(/\(|\)/g,"");
    point = point.split(",");
    point = new google.maps.LatLng(point[0], point[1]);
    poly_points.push(point);
    bounds.extend(point);
    
  });
  
  var polygon_object = new google.maps.Polygon({
    paths: poly_points,
    strokeColor: "#ff8800",
    strokeOpacity: 0.8,
    strokeWeight: 1,
    fillColor: "#000000",
    fillOpacity: 0,
    zIndex: z_index
  });
  
  var center_polygon = new google.maps.Marker({
        position: new google.maps.LatLng(bounds.getCenter().lat(), bounds.getCenter().lng()), 
        map: map,        
        icon: '<?php echo base_url(); ?>image/transparent.png',
        shadow: '<?php echo base_url(); ?>image/transparent.png'  
    });
    //initialize all polygon lable name 
  /*label_polygon = new Label_polygon({
        map: map
  });  
  label_polygon.bindTo('position', center_polygon, 'position');        
  label_polygon.set('text', raw_poly_data.name);*/
  var content_popup = '<a style="color:white" href="<?php echo site_url('network/join_network')?>/' + raw_poly_data.id + '">' +raw_poly_data.jumlah + ' Members - Join Now!</a>';      

  google.maps.event.addListener(polygon_object, 'click', function(){
      window.location = "<?php echo site_url('network/about_network'); ?>/"+raw_poly_data.id;
  });
  google.maps.event.addListener(polygon_object, 'mouseover', function(event){
    polygon_object.setOptions({fillColor : '#008000',strokeWeight: 2,fillOpacity: 0.1});
    //alert(polygon_object.zIndex);
        var bind_position = new google.maps.Marker({
            position: event.latLng, 
            map: map,
            icon: '<?php echo base_url(); ?>image/transparent.png',
            shadow: '<?php echo base_url(); ?>image/transparent.png'
        });
        setTimeout(check_label, 300);
        function check_label(){
            if (document.getElementById('div_network') == null){
                label_popup_polygon = new Label_popup_polygon({
                    map: map
                });
                label_popup_polygon.bindTo('position', bind_position, 'position');         
                label_popup_polygon.set('text_network1', raw_poly_data.name);
                label_popup_polygon.set('text_network2', content_popup);
                setTimeout(hide_popup_polygon, 5000);
            }else if(document.getElementById('div_network').style.display = 'block'){
                document.getElementById('div_network').style.display = 'none';
                label_popup_polygon.unbind('map');
                label_popup_polygon.setMap(null);
                label_popup_polygon = null;
                label_popup_polygon = new Label_popup_polygon({
                    map: map
                });

                label_popup_polygon.bindTo('position', bind_position, 'position');        
                label_popup_polygon.set('text_network1', raw_poly_data.name);
                label_popup_polygon.set('text_network2', content_popup);
                //document.getElementById('div_network').style.display = 'block';
                setTimeout(hide_popup_polygon, 5000);
            }else{
                document.getElementById('div_network').style.display = 'block';
                label_popup_polygon = new Label_popup_polygon({
                    map: map
                });
                label_popup_polygon.bindTo('position', bind_position, 'position');
                label_popup_polygon.set('text_network1', raw_poly_data.name);
                label_popup_polygon.set('text_network2', content_popup);
                setTimeout(hide_popup_polygon, 5000);
            }
        }
  });
  google.maps.event.addListener(polygon_object, 'mouseout', function(){
    polygon_object.setOptions({fillColor : '#000000',strokeWeight: 1,fillOpacity :0 });
  });
   
  polygon_object.setMap(map);
  network_polygons.push(polygon_object);
}

function rebound(path_data){
    var path = path_data.split('#');
    var bounds = new google.maps.LatLngBounds();
    var map_center;
    $.each(path , function(i,point){
        point = point.replace(/\(|\)/g,"");
        point = point.split(",");
        point = new google.maps.LatLng(point[0], point[1]);        
        bounds.extend(point);
        map_center = point;        
    });    
    map.fitBounds(bounds);    
}
--></script>

